﻿using Microsoft.SharePoint;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;

namespace WindStyle.SPEntity.Converters
{
    public class SPFieldLookupValueCollectionConverter : IValueConverter
    {
        public object ToFieldValue(object value, Type targetType, ConversionContext context)
        {
            if (value is ICollection)
            {
                var values = value as ICollection;
                
                Type fieldValueType;
                if (targetType.IsArray)
                    fieldValueType = targetType.GetElementType();
                else
                    fieldValueType = targetType.BaseType.GetGenericArguments()[0];
                var converter = ConverterProvider.GetConverterForField(fieldValueType);

                var result = Activator.CreateInstance(targetType);
                foreach (var item in values)
                {
                    (result as IList).Add(converter.ToFieldValue(item, fieldValueType, context));
                }
                return result;
            }
            return null;
        }

        public object ToPropertyValue(object value, Type targetType, ConversionContext context)
        {
            if (value is IList)
            {
                var valueType = value.GetType();
                var fieldValueType = valueType.BaseType.GetGenericArguments()[0];

                var converter = ConverterProvider.GetConverterForField(fieldValueType);
                if (converter == null)
                    return null;

                Type entityType;
                if (targetType.IsArray)
                    entityType = targetType.GetElementType();
                else
                    entityType = targetType.GetGenericArguments()[0];

                var values = value as IList;
                var results = Activator.CreateInstance(targetType, values.Count) as IList;
                for (int i = 0; i < values.Count; i++)
                {
                    var entity = converter.ToPropertyValue(values[i], entityType, context);
                    if (targetType.IsArray)
                        results[i] = entity;
                    else
                        results.Add(entity);
                }
                return results;
            }
            return null;
        }
    }
}
